package org.frank.blockchain.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import org.frank.blockchain.enums.CommandType;
import org.frank.blockchain.domain.Command;

public class InvokeUtil {

    public static Command invoke(Command command) {
        Object instance = ReflectUtil.newInstance(command.getClassName());
        if (ObjectUtil.isEmpty(instance)) {
            return null;
        }
        Command p2pResponse = new Command();
        p2pResponse.setRequestId(command.getRequestId());
        p2pResponse.setType(CommandType.Response);
        try {
            Object value = ReflectUtil.invoke(instance, command.getMethodName(), command.getArgs().toArray());
            p2pResponse.setData(value);
            p2pResponse.setSuccess(true);
        } catch (Exception e) {
            p2pResponse.setSuccess(false);
            p2pResponse.setErrorMessage(e.getMessage());
        }
        return p2pResponse;
    }
}
